package com.zgm.ch09.jdbc.jdbcTemplate.batchUpdate._4_4;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;


public class JdbcTemplateDemo {

	private JdbcTemplate jdbcTemplate;
	
	
	public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("_4_4-context.xml", JdbcTemplateDemo.class);
        JdbcTemplateDemo demo = (JdbcTemplateDemo) ac.getBean("jdbcTemplateDemo");
        
        demo.runBatch();
//        demo.runUpdate();
    }
	
	private void runBatch() {
		final int count = 200;
		final ArrayList<String> firstNames = new ArrayList<String>();
		final ArrayList<String> lastNames = new ArrayList<String>();
		
		for (int i = 0; i < count; i++) {
			firstNames.add("firstName" + i);
			lastNames.add("lastName" + i);
		}
		
		this.jdbcTemplate.batchUpdate("insert into t_customer (id, first_name, last_name, last_login, comments) values (?, ?, ?, ?, ?)",
				new BatchPreparedStatementSetter() {

					public int getBatchSize() {
						return count;
					}

					public void setValues(PreparedStatement ps, int i)
							throws SQLException {
						ps.setLong(1, i + 2000);
						ps.setString(2, firstNames.get(i));
						ps.setString(3, lastNames.get(i));
						ps.setNull(4, Types.TIMESTAMP);
						ps.setNull(5, Types.CLOB);
					}
					
		});
	}
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

}
